"use strict";
const { logger } = require("ee-core/log");
const { chromium } = require("playwright");
const axios = require("axios");

class BrowserService {
  constructor() {
    logger.info("BrowserService init");
    this.config = {
      userConfig: [{ taskTag: "SP1", browserName: "数据账号" }],
      taskTag: "SP1",
      browserName: "数据账号",
      browserListUrl: "http://127.0.0.1:54345/browser/list",
      browserOpenUrl: "http://127.0.0.1:54345/browser/open",
    };
    this.browserContext = null;
    if (!BrowserService.instance) {
      BrowserService.instance = this;
    }
    return BrowserService.instance;
  }

  static getInstance() {
    if (!BrowserService.instance) {
      BrowserService.instance = new BrowserService();
    }
    return BrowserService.instance;
  }

  /**
   * 检测http服务是否开启
   */
  async getBrowserContext(taskTag) {
    let browserList;
    try {
      browserList = await axios.post(this.config.browserListUrl, {
        page: 0,
        pageSize: 100,
        groupId: "",
      });
      browserList = browserList.data;
    } catch (error) {
      logger.error("http服务未开启", error);
      return null;
    }
    logger.info("获取到浏览器列表:", browserList.data);
    const res = [];
    for (let i = 0; i < this.config.userConfig.length; i++) {
      const userConfig = this.config.userConfig[i];
      if (taskTag && taskTag !== userConfig.taskTag) {
        continue;
      }
      let bitId = browserList.data.list.filter((item) => {
        return item.name === userConfig.browserName;
      })[0]?.id;
      if (!bitId) {
        logger.error(`没有获取到浏览器:${userConfig.browserName}`);
        continue;
      }
      const win = await axios.post(this.config.browserOpenUrl, {
        id: bitId,
      });
      logger.info(`获取到浏览器:${win.data.data.ws}`);
      const browser = await chromium.connectOverCDP(win.data.data.ws);
      return browser.contexts()[0];
    }
    return null;
  }
}

BrowserService.toString = () => "[class BrowserService]";

module.exports = {
  BrowserService,
  browserService: BrowserService.getInstance(),
};
